package com.xuexiang.xhttp2demo.utils;

import android.text.TextUtils;
import android.util.Log;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

import io.reactivex.annotations.NonNull;

/**
 * 加密 解密 相关帮助类
 *
 * @author 何鑫
 * @date 2018/5/24 10:50
 */
public class MDesFiveUtils {

	@NonNull
	public static String md5(String string) {
		if (TextUtils.isEmpty(string)) {
			return "";
		}
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] bytes = md5.digest(string.getBytes());
			StringBuilder result = new StringBuilder();
			for (byte b : bytes) {
				String temp = Integer.toHexString(b & 0xff);
				if (temp.length() == 1) {
					temp = "0" + temp;
				}
				result.append(temp);
			}
			return result.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String generateSign(Map<String, String> paramsMap) {
		// 1、排序，将params不包含sign和face
//		paramsMap.remove("face");
//		paramsMap.remove("sign");
		TreeMap<String, String> paramsSortMap = new TreeMap<>();
		paramsSortMap.putAll(paramsMap);

		// 2、拼接字符串，按照规则：key=valuekey=value
		String paramsStr = "";
		for (String sortKey: paramsSortMap.keySet()) {
			paramsStr += sortKey + "=" + paramsSortMap.get(sortKey);
		}

		paramsStr += "Om29z0bpEhFgBR7aCydXLxoH51luq3c8";

		Log.i("XHttp", "sign->-> "+paramsStr);
		Log.i("XHttp", "sign_md5->-> "+md5(paramsStr).toLowerCase());
		// 3、取字符串的MD5值并反馈
		return md5(paramsStr).toLowerCase();
	}
}